<!DOCTYPE html>
<html>

<head lang="zh-CN">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title></title>
    <style>
        .base {
            height: 200px;
            width: 200px;
            background: pink;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
        }

        p {
            -webkit-user-select: none;
            -moz-user-select: none;
            -ms-user-select: none;
            user-select: none;
        }
    </style>
</head>

<body>
    <div class="base">
        <p>点击触发事件</p>
    </div>
</body>
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.11/lodash.min.js"></script>
<script>
    window.onload = function () {
        function throttle(func, wait, options) {
            var timeout, context, args, result;
            var previous = 0;
            if (!options) options = {};

            var later = function () {
                previous = options.leading === false ? 0 : Date.now() || new Date().getTime();
                timeout = null;
                result = func.apply(context, args);
                if (!timeout) context = args = null;
            };

            var throttled = function () {
                var now = Date.now() || new Date().getTime();
                if (!previous && options.leading === false) previous = now;
                var remaining = wait - (now - previous);
                context = this;
                args = arguments;
                if (remaining <= 0 || remaining > wait) {
                    if (timeout) {
                        clearTimeout(timeout);
                        timeout = null;
                    }
                    previous = now;
                    result = func.apply(context, args);
                    if (!timeout) context = args = null;
                } else if (!timeout && options.trailing !== false) {
                    timeout = setTimeout(later, remaining);
                }
                return result;
            };

            throttled.cancel = function () {
                clearTimeout(timeout);
                previous = 0;
                timeout = context = args = null;
            };

            return throttled;
        }

        function a() {
            console.log(1);
        }
        let b = throttle(a, 1000);
        // let b = _.throttle(a, 2000);
        // setTimeout(b, 0);
        setTimeout(b, 500);
        setTimeout(b, 1800);
        setTimeout(b, 2200);



        function handleClick(e) {
            console.log(this); //this值正确传递
            console.log(e, [...arguments].splice(1)); //参数正确传递
        }

        let handle = throttle(handleClick, 2000);
        // let handle = _.throttle(handleClick, 2000);
        document.querySelector('.base').onclick = handle;
    }

</script>